﻿using GoViewServer.Application.Dtos;
using GoViewServer.Application.Entities;
using System.Text;

namespace GoViewServer.Application.Services
{
    [DynamicApiController]
    public class ViewService
    {
        ISqlSugarClient _db;
        public ViewService(ISqlSugarClient db)
        {
            _db = db;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        [HttpPost("/api/goview/sys/login")]
        public dynamic Login()
        {
            return new
            {
                userinfo = new
                {
                    id = 1,
                    username = "admin",
                    password = "21232f297a57a5a743894a0e4a801fc3",
                    nickname = "管理员",
                    depId = "",
                    posId = "",
                    depName = "",
                    posName = ""
                },
                token = new
                {
                    tokenName = "satoken",
                    tokenValue = "7ce6f8cf-fb02-4225-b160-3caf058e94da",
                    isLogin = true,
                    loginId = 1,
                    loginType = "login",
                    tokenTimeout = 2592000,
                    sessionTimeout = 2592000,
                    tokenSessionTimeout = 2591953,
                    tokenActivityTimeout = -1,
                    loginDevice = "default-device",
                    tag = ""
                }
            };
        }

        /// <summary>
        /// 登出
        /// </summary>
        /// <returns></returns>
        [HttpGet("/api/goview/sys/logout")]
        public dynamic loginout()
        {
            return true;
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost("/oss/object/goview")]
        public async Task<dynamic> goview(IFormFile file)
        {
            var files = App.HttpContext.Request.Form.Files.ToList();

            var filePath = Path.Combine("oss", files[0].FileName);

            using (var fileStream = new FileStream(filePath, FileMode.Create))
            {
                await files[0].CopyToAsync(fileStream);

            }
            var ip = App.Configuration["AppSettings:IP"];
            var port = App.Configuration["AppSettings:Port"];
            return new
            {
                bucketName = "goview",
                key = files[0].FileName,
                objectContent = new
                {
                    httpRequest = new
                    {
                        uri = $"http://{ip}:{port}/oss/{files[0].FileName}"
                    }
                }
            };

        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost("/api/goview/project/upload")]
        public async Task<dynamic> upload(IFormFile file)
        {
            var files = App.HttpContext.Request.Form.Files.ToList();

            var filePath = Path.Combine("oss", files[0].FileName);

            using (var fileStream = new FileStream(filePath, FileMode.Create))
            {
                await files[0].CopyToAsync(fileStream);

            }
            var ip = App.Configuration["AppSettings:Ip"];
            var port = App.Configuration["AppSettings:Port"];
            return new
            {
                bucketName = "",
                createTime = DateTime.Now,
                createUserId = "-",
                createUserName = "-",
                fileName = files[0].FileName,
                fileSize = 0,
                fileSuffix = "image/png",
                id = "",
            };

        }

        /// <summary>
        /// 获取项目列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpGet("/api/goview/project/list"), QueryParameters, NonUnify]
        public async Task<dynamic> list(int page = 1, int limit = 12)
        {
            RefAsync<int> total = 0;
            var res = await _db.Queryable<t_goview_project>()
                .Select(o => new goview_project_list_response()
                {
                    createTime = o.create_time,
                    createUserId = o.create_user_id,
                    id = o.id,
                    indexImage = o.index_image,
                    isDelete = o.is_delete,
                    projectName = o.project_name,
                    remarks = o.remarks,
                    state = o.state
                })
                .ToPageListAsync(page, limit, total);
            return new
            {
                data = res,
                msg = "",
                code = 200,
                count = total.Value
            };
        }

        /// <summary>
        /// 获取项目具体数据
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        [HttpGet("/api/goview/project/getData"), QueryParameters]
        public async Task<dynamic> getData(string projectId)
        {
            var data = await _db.Queryable<t_goview_project_data>()
                .FirstAsync(o => o.project_id == projectId);
            var res = data.Adapt<goview_project_data_response>();
            //res.content = Encoding.Default.GetString(data.content);
            return res;
        }


        /// <summary>
        /// 获取上传地址
        /// </summary>
        /// <returns></returns>
        [HttpGet("/api/goview/sys/getOssInfo")]
        public dynamic getOssInfo()
        {
            var ip = App.Configuration["AppSettings:Ip"];
            var port = App.Configuration["AppSettings:Port"];
            return new
            {
                bucketURL = $"http://{ip}:{port}/oss/",
            };
        }

        /// <summary>
        /// 编辑项目
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost("/api/goview/project/edit")]
        public async Task<dynamic> edit(goview_project_edit_request data)
        {
            var res = await _db.Updateable<t_goview_project>()
                    .SetColumns(o => new t_goview_project() { index_image = data.indexImage })
                    .Where(o => o.id == data.id)
                    .ExecuteCommandAsync();

            return res > 0 ? "操作成功" : throw Oops.Oh("更新失败");
        }

        /// <summary>
        /// 发布项目
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPut("/api/goview/project/publish")]
        public async Task<dynamic> publish(goview_project_publish_request data)
        {
            var res = await _db.Updateable<t_goview_project>()
                    .SetColumns(o => new t_goview_project() { state = data.state })
                    .Where(o => o.id == data.id)
                    .ExecuteCommandAsync();

            return res > 0 ? "操作成功" : throw Oops.Oh("操作失败");
        }

        /// <summary>
        /// 删除项目
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpDelete("/api/goview/project/delete"), QueryParameters]
        public async Task<dynamic> delete(string ids)
        {
            var res = await _db.Deleteable<t_goview_project>()
                    .Where(o => o.id == ids)
                    .ExecuteCommandAsync();

            return res > 0 ? "操作成功" : throw Oops.Oh("操作失败");
        }

        /// <summary>
        /// 保存项目
        /// </summary>
        /// <returns></returns>
        [HttpPost("/api/goview/project/save/data")]
        public async Task<dynamic> save()
        {
            string projectId = App.HttpContext.Request.Form["projectId"];
            string str = App.HttpContext.Request.Form["content"];
            //  var content = Encoding.Default.GetBytes(str);
            var res = await _db.Updateable<t_goview_project_data>()
                    .SetColumns(o => new t_goview_project_data() { content = str })
                    .Where(o => o.id == projectId)
                    .ExecuteCommandAsync();

            return res > 0 ? "数据保存成功" : throw Oops.Oh("数据保存失败");
        }


        /// <summary>
        /// 新建项目
        /// </summary>
        /// <returns></returns>
        [HttpPost("/api/goview/project/create")]
        public async Task<dynamic> create()
        {
            var projectName = Guid.NewGuid().ToString("N");
            var projectId = Guid.NewGuid().ToString("N");
            try
            {
                _db.Ado.BeginTran();
                var project = new t_goview_project()
                {
                    create_time = DateTime.Now,
                    create_user_id = "1",
                    id = projectId,
                    is_delete = -1,
                    project_name = projectName,
                    state = -1
                };
                var res = await _db.Insertable(project).ExecuteCommandAsync();
                var projectData = new t_goview_project_data()
                {
                    // content =Encoding.Default.GetBytes(""),
                    content = "",
                    create_time = DateTime.Now,
                    create_user_id = "1",
                    id = Guid.NewGuid().ToString("N"),
                    project_id = projectId
                };
                var res1 = await _db.Insertable(projectData).ExecuteCommandAsync();
                if (res > 0 && res1 > 0)
                {
                    _db.Ado.CommitTran();
                    return new goview_project_list_response()
                    {
                        createTime = DateTime.Now,
                        state = -1,
                        id = projectId,
                        isDelete = -1,
                    };
                }
                else
                {
                    _db.Ado.RollbackTran();
                    throw Oops.Oh("创建失败");
                }

            }
            catch (Exception ex)
            {

                throw Oops.Oh(ex.Message);
            }




        }
    }
}